package cn.myit.interceptor;

import cn.myit.service.impl.LoginServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class MyLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private LoginServiceImpl loginService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        String token = request.getHeader("token");
        if ("null".equals(token)){
            PrintWriter writer = response.getWriter();
            writer.write("{\"code\":\"401\",\"success\":false}");
            return false;
        }
        if(!loginService.getMap().containsKey(token)){
            PrintWriter writer = response.getWriter();
            writer.write("{\"code\":\"401\",\"success\":false}");
            return false;
        }
        return true;
    }
}
